package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.MODE_PRIVATE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static java.lang.Math.round;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentC extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentC.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_WEIGHT=9002;
    public static final int MSG_CALCWEIGHT=9003;
    public static final int MSG_CHECKPASS=9004;
    public static final int MSG_SEARCHOVER=9005;
    public static final int MSG_CANCELPASS=9006;
    public static final int MSG_ERRMSG = 9999;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,WeightStr;
    Button btn_find,btn_Query,btn_EditNum,btn_CalcSingle,btn_Depart;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_PackNo,txt_Size,txt_StyleSort,txt_SonPertain,txt_Number;
    TextView txt_SingleWeight,txt_ExpectWeight,txt_ExpectPiece,txt_RealWeight,txt_RealPiece;
    CheckBox check_AutoSave;
    Button btn_Save,btn_Select,btn_Cancel;
    Button btn_AfterSewReceive,btn_StampOut,btn_StampIn,btn_GarmentOut;
    TextView txt_SelectType,tv_CheckResult;
    TextView txt_RecTotalPiece,txt_RecOwenPiece,txt_RecTodayPiece,txt_CurTotalPiece;
    EditText edt_barcode,edt_SearchStyleNo,edt_FormDate;
    JSONArray resultJSON,headJSON,detailJSON,orderJSON,departJSON;
    String selectRSType="",PrBarcode="",selDepartmentNo="",selDepartment="";
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selOrderNo="",selStyleNo="",selPO="",selColor="",selSize="",selStyleSort="",selSingleWeight="",selSonPertain="",selNumber="",selAutoSave="";

    boolean NeedCheck=false;
    int PrWeight=0;
    private FragmentCCallBack mFragmentCCallBack;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public interface FragmentCCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentCWorkAndTransParams(Map<String, Object> Params);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentCCallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentCCallBack接口");
        }
        mFragmentCCallBack=(FragmentCCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentCCallBack=null;
    }

    //消息回调
    public void ToSpeech(String paramText){
        //传消息给主界面;
        if (mFragmentCCallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","Speech");//命令;
            fragmentParams.put("Text",paramText);//命令;
            mFragmentCCallBack.FragmentCWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");
    }
    public FragmentC() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerC(new MainActivity.OnTransParamsListenerC() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            detailJSON=new JSONArray("[]");
                            getDepartment(curDepart);
                        }
                        if (paramComm=="Weight")
                        {
                            WeightStr=mParams.get("Weight").toString();
                            if (isNumeric(WeightStr)==true){
                                if ((Integer.valueOf(WeightStr)<20)&(PrWeight>20)) {
                                    NeedCheck=true;
                                    btn_Save.setEnabled(true);
                                }
                                PrWeight=Integer.valueOf(WeightStr);
                            }
                            //发消息置焦点
                            Message msg =new Message();
                            Bundle bdl=new Bundle();
                            bdl.putString("Weight",WeightStr);
                            msg.setData(bdl);
                            msg.what = MSG_WEIGHT;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_c, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        btn_Depart=view.findViewById(R.id.btn_Depart);
        btn_Depart.setOnClickListener(this);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Cancel=view.findViewById(R.id.btn_Cancel);
        btn_Cancel.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        txt_RealWeight=view.findViewById(R.id.txt_RealWeight);
        txt_RealWeight.setOnClickListener(this);
        tv_CheckResult=view.findViewById(R.id.tv_CheckResult);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        playRingtone();
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            //执行查询;
                            /*if (selDepartment.length()==0){
                                curToast.setText(getString(R.string.plsSelectRecSendDepart));
                                curToast.show();
                            } else
                             */
                            if (txt_SelectType.getText().toString().length() == 0) {
                                curToast.setText(getString(R.string.PlsSelectRSType));
                                curToast.show();
                            } else {
                                String scanType = "Single";
                                searchBarcodeData(edt_barcode.getText().toString(), txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(), selectRSType, scanType);
                            }
                        }
                        //未有焦点
                        //发消息置焦点
                        Message msg =new Message();
                        msg.what = msgFocusBarcode;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }

                }
                return false;
            }
        });


        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_PackNo=view.findViewById(R.id.txt_PackNo);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_Number=view.findViewById(R.id.txt_Number);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_SonPertain=view.findViewById(R.id.txt_SonPertain);

        check_AutoSave=view.findViewById(R.id.check_AutoSave);
        check_AutoSave.setOnClickListener(this);
        btn_Save=view.findViewById(R.id.btn_Save);
        btn_Save.setOnClickListener(this);
        btn_Select=view.findViewById(R.id.btn_Select);
        btn_Select.setOnClickListener(this);
        edt_SearchStyleNo=view.findViewById(R.id.edt_SearchStyleNo);

        btn_AfterSewReceive=view.findViewById(R.id.btn_AfterSewReceive);
        btn_AfterSewReceive.setOnClickListener(this);
        btn_StampOut=view.findViewById(R.id.btn_StampOut);
        btn_StampOut.setOnClickListener(this);
        btn_StampIn=view.findViewById(R.id.btn_StampIn);
        btn_StampIn.setOnClickListener(this);
        view.findViewById(R.id.btn_EmbroiderIn).setOnClickListener(this);
        view.findViewById(R.id.btn_EmbroiderOut).setOnClickListener(this);
        btn_GarmentOut=view.findViewById(R.id.btn_GarmentOut);
        btn_GarmentOut.setOnClickListener(this);
        txt_SelectType=view.findViewById(R.id.txt_SelectType);
        txt_SelectType.setOnClickListener(this);

        btn_EditNum=view.findViewById(R.id.btn_EditNum);
        btn_EditNum.setOnClickListener(this);
        btn_CalcSingle=view.findViewById(R.id.btn_CalcSingle);
        btn_CalcSingle.setOnClickListener(this);
        txt_SingleWeight=view.findViewById(R.id.txt_SingleWeight);
        txt_SingleWeight.setOnClickListener(this);
        txt_ExpectWeight=view.findViewById(R.id.txt_ExpectWeight);
        txt_ExpectPiece=view.findViewById(R.id.txt_ExpectPiece);
        txt_RealWeight=view.findViewById(R.id.txt_RealWeight);
        txt_RealPiece=view.findViewById(R.id.txt_RealPiece);

        txt_RecTotalPiece=view.findViewById(R.id.txt_RecTotalPiece);
        txt_RecOwenPiece=view.findViewById(R.id.txt_RecOwenPiece);
        txt_RecTodayPiece=view.findViewById(R.id.txt_RecTodayPiece);
        txt_CurTotalPiece=view.findViewById(R.id.txt_CurTotalPiece);
        txt_CurTotalPiece.setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String EndDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edt_FormDate=view.findViewById(R.id.edt_FormDate);
        edt_FormDate.setText(EndDateStr);
        edt_FormDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(view.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_FormDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择接收日期");
                mDialog.show();
            }
        });

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam,String RSTypeParam,String ScanTypeParam)
    {
        clearFormText();
        NeedCheck=true;
        //执行SQL过程
        PrBarcode=BarcodeParam;
        String SqlComm="Exec KeyPoint_SendRecBarcode @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@RSType='" + RSTypeParam+ "',@ScanType='" + ScanTypeParam+"',@FormDate='"+edt_FormDate.getText().toString()+"',@Depart='"+selDepartment
                + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新缸布列表;
    private void searchStyleNoData(String SearchParam)
    {
        String SqlComm="Exec KeyPoint_SendRecSearchStyleNo @SearchParam='" + SearchParam + "',@OPERTYPE='SEARCH',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //测算克重
    private void calcBarcodeData(String BarcodeParam,String WeightParam)
    {
        //执行SQL过程
        if ((txt_OrderNo.getText()!=null)&&(txt_StyleNo.getText()!=null)&&(txt_SonPertain.getText()!=null)&&(txt_Color.getText()!=null)&&(txt_Size.getText()!=null)) {
            String SqlComm = "Exec KeyPoint_CalcWeight @Barcode='" + BarcodeParam + "',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString()
                    + "',@SonPertain='" + txt_SonPertain.getText().toString() + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString()
                    + "',@Number='" + txt_Number.getText().toString()
                    + "',@Weight='" + WeightParam + "',@OPERTYPE='CALCWEIGHT',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else{
            curToast.setText("请先扫描条码或选择合约!");
            curToast.show();
        }
    }

    //测算克重
    private void CheckPassBarcode(String BarcodeParam,String OrderNoParam,String StyleNoParam,String POParam,String SonPertainParam,String ColorParam,String SizeParam,String PieceParam,String WeightParam,String RSTypeParam,String ScanTypeParam)
    {
        NeedCheck=false;
        if (txt_SelectType.getText().toString().length() == 0) {
            curToast.setText(getString(R.string.PlsSelectRSType));
            curToast.show();
            ToSpeech(getString(R.string.PlsSelectRSType));
            return;
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SendRecPass @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam+ "',@StyleNo='" + StyleNoParam
                + "',@PO='" + POParam+ "',@SonPertain='" + SonPertainParam
                + "',@Color='" + ColorParam+ "',@Size='" + SizeParam
                + "',@Piece='" + PieceParam+ "',@Weight='" + WeightParam + "',@RSType='" + RSTypeParam+"',@FormDate='"+edt_FormDate.getText().toString()
                + "',@ScanType='" + ScanTypeParam+ "',@Depart='" + selDepartment+ "',@OPERTYPE='CHECKPASS',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void CancelPassBarcode(String BarcodeParam,String OrderNoParam,String StyleNoParam,String POParam,String SonPertainParam,String ColorParam,String SizeParam,String PieceParam,String WeightParam,String RSTypeParam,String ScanTypeParam)
    {
        String curTotalPiece="";
        if (txt_CurTotalPiece.getText()==null) curTotalPiece="";
        else curTotalPiece=txt_CurTotalPiece.getText().toString();
        System.out.println("Exec CancelPassBarcode-Start");
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SendRecCancel @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam+ "',@StyleNo='" + StyleNoParam
                + "',@PO='" + POParam+ "',@SonPertain='" + SonPertainParam
                + "',@Color='" + ColorParam+ "',@Size='" + SizeParam
                + "',@Piece='" + PieceParam+ "',@Weight='" + WeightParam + "',@RSType='" + RSTypeParam
                + "',@ScanType='" + ScanTypeParam+ "',@CurTotalPiece='" + curTotalPiece+"',@FormDate='"+edt_FormDate.getText().toString()
                + "',@Depart='" + selDepartment+ "',@OPERTYPE='CANCELPASS',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        System.out.println("SqlComm:"+SqlComm);
        ReadSQLData(SqlComm);
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //显示实际件数
    private void showEditNumer(){
        //创建布局
        String pieceNum="0",pingleWeight="0";
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.fragment_c_editnum, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        try {
            //临时加载
            final EditText text_pieceNum=pull_input.findViewById(R.id.text_pieceNum);
            text_pieceNum.setText(txt_Number.getText().toString());
            text_pieceNum.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
            text_pieceNum.selectAll();
            if (txt_SingleWeight.getText()!=null) pingleWeight=txt_SingleWeight.getText().toString();
            //创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            final String finalPingleWeight = pingleWeight;
            builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                if (text_pieceNum.getText().toString().length() > 0)
                                    txt_Number.setText(text_pieceNum.getText().toString());
                                txt_ExpectPiece.setText(text_pieceNum.getText().toString());
                                System.out.println("1");
                                int expectWeight= round(Float.valueOf(finalPingleWeight) * Integer.valueOf(text_pieceNum.getText().toString()));
                                txt_ExpectWeight.setText(String.valueOf(expectWeight));
                                System.out.println("2");
                                System.out.println("预估重量:"+expectWeight);
                                hideIM(pull_input);
                                NeedCheck = true;
                                CheckPass();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
            ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    hideIM(pull_input);
                    Log.v("tag","取消");
                }
            }).setTitle("博大EFS系统");
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.txt_RealWeight:
                txt_RealWeight.setText("0");
                txt_RealPiece.setText("0");
                NeedCheck=true;
                break;
            case R.id.btn_Cancel:
                if ((txt_OrderNo.getText()!=null)&&(txt_StyleNo.getText()!=null)&&(txt_OrderNo.getText()!=null)) {
                    new AlertDialog.Builder(getContext()).setTitle("系统提示")
                            .setMessage("您确定要撤消前一条称重记录吗？")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    CancelPassBarcode(PrBarcode, txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(), txt_PO.getText().toString(), txt_SonPertain.getText().toString(),
                                            txt_Color.getText().toString(), txt_Size.getText().toString(), txt_RealPiece.getText().toString(), txt_RealWeight.getText().toString(), selectRSType, "Single");
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    }).show();
                } else {
                    curToast.setText("未有制单信息,不能撤消!");
                    curToast.show();
                }
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else //执行查询;
                {
                    if (txt_SelectType.getText().toString().length() == 0) {
                        curToast.setText(getString(R.string.PlsSelectRSType));
                        curToast.show();
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    } else {
                        String scanType = "Single";
                        searchBarcodeData(edt_barcode.getText().toString(), txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(), selectRSType, scanType);
                    }
                }
                break;
            case R.id.btn_Select:
                String searchStyleNo="";
                PrBarcode="NOBARCODE";
                if ((edt_SearchStyleNo.getText()!=null)&&(edt_SearchStyleNo.getText().toString().length()>0)) searchStyleNo=edt_SearchStyleNo.getText().toString();
                searchStyleNoData(searchStyleNo);
                break;
            case R.id.btn_Save:
                System.out.println("btn_save 执行");
                //件数相同的
                if ((txt_RealPiece.getText()==null)||(txt_ExpectPiece.getText()==null)){
                    curToast.setText(R.string.plsSelectOrderAndWeight);
                    curToast.show();
                    ToSpeech((String) getResources().getText(R.string.plsSelectOrderAndWeight));
                    return;
                }
                if (selDepartment.length()==0){
                    curToast.setText(R.string.plsSelectRecSendDepart);
                    curToast.show();
                    ToSpeech((String) getResources().getText(R.string.plsSelectRecSendDepart));
                    return;
                }
                if (txt_RealPiece.getText().toString().equals(txt_ExpectPiece.getText().toString())) {
                    System.out.println("数量符合要求");
                    CheckPassBarcode(PrBarcode,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_PO.getText().toString(),txt_SonPertain.getText().toString(),txt_Color.getText().toString(),txt_Size.getText().toString(), txt_RealPiece.getText().toString(), txt_RealWeight.getText().toString(), selectRSType,"Single");
                } else {
                    curToast.setText(R.string.realNumberNotEquals);
                    curToast.show();
                    ToSpeech(getResources().getString(R.string.realNumberNotEquals));
                }
                btn_Save.setEnabled(false);
                break;
            case R.id.txt_SingleWeight:
                //手工输入克重
                if (txt_SingleWeight.getText()!=null) showEditWeight(txt_SingleWeight.getText().toString());
                else showEditWeight("");
                break;
            case R.id.btn_AfterSewReceive:
                txt_SelectType.setText(btn_AfterSewReceive.getText());
                selectRSType="AfterSew";
                NeedCheck=true;
                hideIM(v);
                break;
            case R.id.btn_StampOut:
                txt_SelectType.setText("印花发出");
                selectRSType="StampOut";
                NeedCheck=true;
                hideIM(v);
                break;
            case R.id.btn_StampIn:
                txt_SelectType.setText("印花接收");
                selectRSType="StampIn";
                NeedCheck=true;
                hideIM(v);
                break;
            case R.id.btn_EmbroiderIn:
                txt_SelectType.setText("绣花接收");
                selectRSType="EmbroiderIn";
                NeedCheck=true;
                break;
            case R.id.btn_EmbroiderOut:
                txt_SelectType.setText("绣花发出");
                selectRSType="EmbroiderOut";
                NeedCheck=true;
                break;
            case R.id.btn_GarmentOut:
                txt_SelectType.setText("其他接收");
                selectRSType="GarmentOut";
                NeedCheck=true;
                hideIM(v);
                break;
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "后整接收");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.check_AutoSave:
                //读取配置文件-设置语言String STORE_NAME = "";
                SharedPreferences settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
                SharedPreferences.Editor set_editor=settings.edit();
                set_editor.putBoolean("AutoSave",check_AutoSave.isChecked());
                set_editor.commit();
                break;
            case R.id.btn_EditNum:
                showEditNumer();
                break;
            case R.id.btn_CalcSingle:
                if ((txt_RealWeight.getText()!=null)&&(txt_ExpectPiece.getText()!=null)&&(txt_RealWeight.getText().toString().length()>0)&&(txt_ExpectPiece.getText().toString().length()>0)){
                    if (Integer.valueOf(txt_RealWeight.getText().toString())>0){
                        if (isNumeric(txt_ExpectPiece.getText().toString())==true){
                            if (Integer.valueOf(txt_ExpectPiece.getText().toString())>0) {
                                txt_ExpectWeight.setText(txt_RealWeight.getText().toString());
                                txt_RealPiece.setText(txt_ExpectPiece.getText().toString());
                                txt_SingleWeight.setText(String.format("%.2f",Float.valueOf(txt_RealWeight.getText().toString()) / Float.valueOf(txt_ExpectPiece.getText().toString())));
                                //检查重量
                                CheckPass();
                                //更新单件克重;
                                calcBarcodeData(PrBarcode, txt_RealWeight.getText().toString());
                            }
                        }
                    } else {
                        curToast.setText(R.string.PlsConnectBalance);
                        curToast.show();
                        ToSpeech((String) getResources().getText(R.string.PlsConnectBalance));
                    }
                } else {
                    curToast.setText(R.string.PlsConnectBalance);
                    ToSpeech((String) getResources().getText(R.string.PlsConnectBalance));
                    curToast.show();
                }
                break;
            case R.id.txt_CurTotalPiece:
                txt_CurTotalPiece.setText("0");
                break;
            case R.id.btn_Depart:
                if (departJSON!=null) showSelectDepart();
                else getDepartment(curDepart);
                break;
            default:
                break;
        }
    }

    //刷新缸布列表;
    private void getDepartment(String paramWorkShop)
    {
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_SendRecGetDepart @OPERTYPE='GETDEPART',@WorkShop='"+paramWorkShop+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    //显示工序选择
    private void showSelectDepart(){
        if (departJSON==null) {
            ToSpeech("没有找到组别信息!");
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"WorkShop\",\"TitleText\":\"车间\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"DepartmentNo\",\"TitleText\":\"组别编号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Department\",\"TitleText\":\"组别名称\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="组别选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        detailJSON=departJSON;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(position).has("DepartmentNo")==true)
                        selDepartmentNo=detailJSON.optJSONObject(position).getString("DepartmentNo");
                    if (detailJSON.optJSONObject(position).has("Department")==true)
                        selDepartment=detailJSON.optJSONObject(position).getString("Department");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selDepartmentNo.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            btn_Depart.setText(selDepartment);
                            NeedCheck=true;
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selDepartment="";
                    selDepartmentNo="";
                    btn_Depart.setText("请选择组别");
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 450;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }
    //显示工序选择
    private void showSelectOrder(){
        if (orderJSON==null) {
            ToSpeech("没有找到制单信息!");
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"OrderNo\",\"TitleText\":\"制单号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"StyleNo\",\"TitleText\":\"款号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"SonPertain\",\"TitleText\":\"子件\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"PO\",\"TitleText\":\"PO\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Color\",\"TitleText\":\"颜色\",\"TxtSize\":18,\"TxtWidth\":200,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Size\",\"TitleText\":\"尺码\",\"TxtSize\":18,\"TxtWidth\":50,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"SingleWeight\",\"TitleText\":\"克重\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":2,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"Number\",\"TitleText\":\"件数\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":2,\"Color\":\"Blue\"}]");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="合约选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        detailJSON=orderJSON;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(position).has("OrderNo")==true)
                        selOrderNo=detailJSON.optJSONObject(position).getString("OrderNo");
                    if (detailJSON.optJSONObject(position).has("StyleNo")==true)
                        selStyleNo=detailJSON.optJSONObject(position).getString("StyleNo");
                    if (detailJSON.optJSONObject(position).has("StyleSort")==true)
                        selStyleSort=detailJSON.optJSONObject(position).getString("StyleSort");
                    if (detailJSON.optJSONObject(position).has("PO")==true)
                        selPO=detailJSON.optJSONObject(position).getString("PO");
                    if (detailJSON.optJSONObject(position).has("Color")==true)
                        selColor=detailJSON.optJSONObject(position).getString("Color");
                    if (detailJSON.optJSONObject(position).has("Size")==true)
                        selSize=detailJSON.optJSONObject(position).getString("Size");
                    if (detailJSON.optJSONObject(position).has("SingleWeight")==true)
                        selSingleWeight=detailJSON.optJSONObject(position).getString("SingleWeight");
                    if (detailJSON.optJSONObject(position).has("SonPertain")==true)
                        selSonPertain=detailJSON.optJSONObject(position).getString("SonPertain");
                    if (detailJSON.optJSONObject(position).has("Number")==true)
                        selNumber=detailJSON.optJSONObject(position).getString("Number");
                    if (detailJSON.optJSONObject(position).has("AutoSave")==true)
                        selAutoSave=detailJSON.optJSONObject(position).getString("AutoSave");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selOrderNo.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            txt_OrderNo.setText(selOrderNo);
                            txt_StyleNo.setText(selStyleNo);
                            txt_StyleSort.setText(selStyleSort);
                            txt_PO.setText(selPO);
                            txt_Color.setText(selColor);
                            txt_Size.setText(selSize);
                            txt_PackNo.setText("****");
                            txt_SonPertain.setText(selSonPertain);
                            txt_SingleWeight.setText(selSingleWeight);
                            txt_Number.setText(selNumber);
                            txt_ExpectPiece.setText(selNumber);
                            check_AutoSave.setChecked(selAutoSave.equals("YES"));
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selOrderNo="";
                    selStyleNo="";
                    selStyleSort="";
                    selPO="";
                    selSize="";
                    selColor="";
                    selSingleWeight="";
                    selSonPertain="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 1100;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }


    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (detailJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = detailJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (detailJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= detailJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }



    private void showEditWeight(final String weightParam){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.weight_input, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        try {
            //临时加载
            final EditText edt_SingleWeight=pull_input.findViewById(R.id.edt_SingleWeight);
            edt_SingleWeight.setText(weightParam);
            //创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            txt_SingleWeight.setText(edt_SingleWeight.getText().toString());
                            calcBarcodeData(PrBarcode,edt_SingleWeight.getText().toString());
                            hideIM(pull_input);
                        }
                    }
            ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    hideIM(pull_input);
                    Log.v("tag","取消");
                }
            }).setTitle(getResources().getString(R.string.app_name));
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //检查是否通过
    private void CheckPass() {
        boolean passSign=false;
        if (selDepartment.length()==0){
            tv_CheckResult.setText("请选组别");
            tv_CheckResult.setTextColor(Color.RED);
            tv_CheckResult.setBackgroundColor(Color.WHITE);
            return;
        }
        if (NeedCheck){
            tv_CheckResult.setTextColor(Color.YELLOW);
            if ((txt_ExpectWeight.getText()!=null)&&(txt_ExpectPiece.getText()!=null)&&(txt_RealWeight.getText()!=null)&&(txt_SingleWeight.getText()!=null)){
                if (isNumeric(txt_ExpectWeight.getText().toString())&&isNumeric(txt_ExpectPiece.getText().toString())
                        &&isNumeric(txt_RealWeight.getText().toString())&&isNumeric(txt_SingleWeight.getText().toString()))
                {
                    if ((Integer.valueOf(txt_ExpectPiece.getText().toString())>0)&&(Integer.valueOf(txt_ExpectWeight.getText().toString())>0)&&(Float.valueOf(txt_SingleWeight.getText().toString())>0)){
                        if (Integer.valueOf(txt_RealWeight.getText().toString())>0){
                            int owenWeight;
                            if (Integer.valueOf(txt_RealWeight.getText().toString())>=Integer.valueOf(txt_ExpectWeight.getText().toString()))
                                owenWeight=Integer.valueOf(txt_RealWeight.getText().toString())-Integer.valueOf(txt_ExpectWeight.getText().toString());
                            else
                                owenWeight=Integer.valueOf(txt_ExpectWeight.getText().toString())-Integer.valueOf(txt_RealWeight.getText().toString());
                            //误差小于1件的一半的
                            if (owenWeight<Float.valueOf(txt_SingleWeight.getText().toString())/2){
                                txt_RealPiece.setText(txt_ExpectPiece.getText().toString());
                            } else{
                                txt_RealPiece.setText(String.valueOf(round(Float.valueOf(txt_RealWeight.getText().toString())/Float.valueOf(txt_SingleWeight.getText().toString()))));
                            }
                            //件数相同的
                            if (txt_RealPiece.getText().toString().equals(txt_ExpectPiece.getText().toString())) {
                                System.out.println("数量符合要求");
                                passSign=true;
                            }
                        }
                    }
                }
            }
            if (! passSign){
                if ((txt_RealPiece.getText().toString().equals("0"))&&(txt_RealWeight.getText().toString().equals("0")))
                {
                    tv_CheckResult.setText("请放成品");
                    tv_CheckResult.setBackgroundColor(Color.BLUE);
                } else {
                    tv_CheckResult.setText("数量不符");
                    tv_CheckResult.setBackgroundColor(Color.RED);
                }
            } else{
                tv_CheckResult.setText("数量相符");
                tv_CheckResult.setBackgroundColor(Color.GREEN);
                if (check_AutoSave.isChecked()) ToSpeech("数量相符");
                else ToSpeech("数量相符,请点击保存!");
                NeedCheck=false;
                if (txt_CurTotalPiece.getText()!=null){
                    System.out.println("txt_CurTotalPiece 准备计算");
                    System.out.println(txt_CurTotalPiece.getText().toString());
                    int CurTotalPiece=Integer.valueOf(txt_CurTotalPiece.getText().toString());
                    System.out.println("txt_CurTotalPiece A:"+CurTotalPiece);
                    int RealPiece=Integer.valueOf(txt_RealPiece.getText().toString());
                    System.out.println("txt_CurTotalPiece B:"+RealPiece);
                    txt_CurTotalPiece.setText(String.valueOf(CurTotalPiece+RealPiece));
                } else System.out.println("txt_CurTotalPiece 为空");
                //调用过程;
                String scanType = "Single";
                if (check_AutoSave.isChecked()) {
                    CheckPassBarcode(PrBarcode,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_PO.getText().toString(),txt_SonPertain.getText().toString(),
                            txt_Color.getText().toString(),txt_Size.getText().toString(), txt_RealPiece.getText().toString(), txt_RealWeight.getText().toString(), selectRSType,scanType);
                }
            }
        }
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                String tmpValue;
                //任意消息来均置焦点
                int msgId = msg.what;
                if (msgId!=MSG_WEIGHT) {
                    if (edt_barcode.isFocused() == false) setEditBarcodeFocus();
                    else edt_barcode.selectAll();
                }
                System.out.println("收到的消息是："+msg.what);
                tmpValue= (String) msg.getData().get("Weight");
                String resultMsg="";
                switch (msgId) {
                    case MSG_ERRMSG:
                        //提示提交完成，需确认;
                        Bundle bundle1=msg.getData();
                        resultMsg=bundle1.getString("Hint");
                        // 创建对话框
                        AlertDialog alertDialoghint = new AlertDialog.Builder(getContext())
                                .setTitle("系统提示").setMessage(resultMsg)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialoghint.show(); // 显示对话框
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext();
                        break;
                    case MSG_WEIGHT:
                        txt_RealWeight.setText(tmpValue);
                        if (txt_SingleWeight.getText()!=null){
                            if (isNumeric(txt_SingleWeight.getText().toString()))
                                if (Float.valueOf(txt_SingleWeight.getText().toString())>0)
                                    txt_RealPiece.setText(String.valueOf(round(Float.valueOf(txt_RealWeight.getText().toString())/Float.valueOf(txt_SingleWeight.getText().toString()))));
                                else txt_RealPiece.setText("0");
                        } else txt_RealPiece.setText("0");
                        CheckPass();
                        break;
                    case MSG_CANCELPASS:
                        fillFormtext();
                        break;
                    case MSG_CALCWEIGHT:
                        fillFormtext();
                        break;
                    case MSG_CHECKPASS:
                        fillFormtext();

                        break;
                    case MSG_SEARCHOVER:
                        showSelectOrder();
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SCANBARCODE")) {
                                resultJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SCANBARCODE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("CALCWEIGHT"))
                            {
                                resultJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_CALCWEIGHT;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("CHECKPASS"))
                            {
                                resultJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_CHECKPASS;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SEARCH"))
                            {
                                orderJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SEARCHOVER;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("GETDEPART")) {
                                departJSON= jsonArray;
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("CANCELPASS")){
                                resultJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_CANCELPASS;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            fragmentHandler.sendMessage(message);
                        }

                    } else {
                        Message message = new Message();
                        message.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何数据!");
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage().toString());
                    message.setData(bundle);
                    fragmentHandler.sendMessage(message);
                }

            }

        };
        new Thread(run).start();
    }





    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_PackNo.setText("");
        txt_Size.setText("");
        txt_StyleSort.setText("");
        txt_SonPertain.setText("");
        txt_Number.setText("");
        txt_HintInfo.setText("");
        txt_ExpectPiece.setText("");
        txt_ExpectWeight.setText("");
        txt_RealWeight.setText("");
        txt_RealPiece.setText("");
        txt_RecTotalPiece.setText("");
        txt_RecOwenPiece.setText("");
        txt_RecTodayPiece.setText("");
        tv_CheckResult.setText("??");
        tv_CheckResult.setBackgroundColor(Color.GRAY);
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                if (resultJSON.getJSONObject(0).has("selDepartment")==true) {
                    selDepartment=resultJSON.getJSONObject(0).getString("selDepartment");
                    btn_Depart.setText(selDepartment);
                }
                //保存提交
                if (resultJSON.optJSONObject(0).has("RESULT")==true){
                    NeedCheck=false;
                    if (resultJSON.optJSONObject(0).getString("RESULT").equals("OK")) {
                        if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                        if (resultJSON.optJSONObject(0).has("INFO")) {
                            tv_CheckResult.setText(resultJSON.optJSONObject(0).getString("INFO"));
                        } else tv_CheckResult.setText("通过");
                        tv_CheckResult.setBackgroundColor(getResources().getColor(R.color.text_green));
                        //语音播报;
                        ToSpeech(tv_CheckResult.getText().toString());
                    }
                }
                //别的参数刷新
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                if (resultJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                if (resultJSON.getJSONObject(0).has("PackNo")==true) txt_PackNo.setText(resultJSON.getJSONObject(0).getString("PackNo"));
                if (resultJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJSON.getJSONObject(0).getString("Size"));
                if (resultJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(resultJSON.getJSONObject(0).getString("StyleSort"));
                if (resultJSON.getJSONObject(0).has("SonPertain")==true) txt_SonPertain.setText(resultJSON.getJSONObject(0).getString("SonPertain"));
                if (resultJSON.getJSONObject(0).has("Number")==true) {
                    txt_Number.setText(resultJSON.getJSONObject(0).getString("Number"));
                    txt_ExpectPiece.setText(resultJSON.getJSONObject(0).getString("Number"));
                }
                if (resultJSON.getJSONObject(0).has("SingleWeight")==true) txt_SingleWeight.setText(resultJSON.getJSONObject(0).getString("SingleWeight"));
                if (resultJSON.getJSONObject(0).has("ExpectWeight")==true) {
                    txt_ExpectWeight.setText(resultJSON.getJSONObject(0).getString("ExpectWeight"));
                    if (resultJSON.getJSONObject(0).getString("ExpectWeight").equals("0")) {
                        NeedCheck=true;
                        tv_CheckResult.setText("请放成品");
                        tv_CheckResult.setBackgroundColor(Color.BLUE);
                    }
                }
                if (resultJSON.getJSONObject(0).has("RealWeight")==true) txt_RealWeight.setText(resultJSON.getJSONObject(0).getString("RealWeight"));
                if (resultJSON.getJSONObject(0).has("RealPiece")==true) txt_RealPiece.setText(resultJSON.getJSONObject(0).getString("RealPiece"));
                if (resultJSON.getJSONObject(0).has("RecTotalPiece")==true) txt_RecTotalPiece.setText(resultJSON.getJSONObject(0).getString("RecTotalPiece"));
                if (resultJSON.getJSONObject(0).has("RecOwenPiece")==true) txt_RecOwenPiece.setText(resultJSON.getJSONObject(0).getString("RecOwenPiece"));
                if (resultJSON.getJSONObject(0).has("RecTodayPiece")==true) txt_RecTodayPiece.setText(resultJSON.getJSONObject(0).getString("RecTodayPiece"));
                if (resultJSON.getJSONObject(0).has("CurTotalPiece")==true) txt_CurTotalPiece.setText(resultJSON.getJSONObject(0).getString("CurTotalPiece"));

                if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }

    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden==false){
            //读配置文件
            System.out.println("Read Set AutoSave");
            SharedPreferences settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
            check_AutoSave.setChecked(settings.getBoolean("AutoSave",true));
        }
    }
}
